﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using VisionBasicSystem.Commons;

namespace VisionBasicSystem.Dal
{
    public class UserInfoDal
    {
        /// <summary>
        /// 根据用户的编号，获取用户的信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserInfo GetUserInfo(int id)
        {
            string sql = "select * from UserInfo where ID=@ID";
            SqlParameter[] pars = { new SqlParameter("@ID", SqlDbType.Int) };
            pars[0].Value = id;
            DataTable da = SqlHelper.GetDataTable(sql, CommandType.Text, pars);
            UserInfo userInfo = null;
            if (da.Rows.Count > 0)
            {
                userInfo = new UserInfo();
                LoadEntity(userInfo, da.Rows[0]);
            }
            return userInfo;
        }

        //1.根据用户名查询密码

        /// <summary>
        /// 根据用户的用户名，获取用户的信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserInfo GetUserInfo(string userName)
        {
            string sql = "select * from UserInfo where UserName=@UserName";
            SqlParameter[] pars = { new SqlParameter("@UserName", SqlDbType.NVarChar, 32) };
            pars[0].Value = userName;
            DataTable da = SqlHelper.GetDataTable(sql, CommandType.Text, pars);
            UserInfo userInfo = null;
            if (da.Rows.Count > 0)
            {
                userInfo = new UserInfo();
                LoadEntity(userInfo, da.Rows[0]);
            }
            return userInfo;
        }

        //2.修改密码

        //获取用户列表
        public List<UserInfo> GetList()
        {
            string sql = "select * from userinfo";
            DataTable da = MySqlHelperUtil.GetDataTable(sql, CommandType.Text);
            List<UserInfo> list = null;
            if (da.Rows.Count > 0)
            {
                list = new List<UserInfo>();
                UserInfo userInfo = null;
                foreach (DataRow row in da.Rows)
                {
                    userInfo = new UserInfo();
                    LoadEntity(userInfo, row);
                    list.Add(userInfo);
                }
            }
            return list;
        }

        //将row中的数据赋值给userinfo的属性
        private void LoadEntity(UserInfo userInfo, DataRow row)
        {
            userInfo.Id = Convert.ToInt32(row["id"]);
            userInfo.UserName = row["user_name"] != DBNull.Value ? row["user_name"].ToString() : string.Empty;
            userInfo.Password = row["password"] != DBNull.Value ? row["password"].ToString() : string.Empty;
            userInfo.LoginTime = Convert.ToDateTime(row["login_time"]);
        }
    }
}